/* eslint-disable no-unused-vars */
import WebsocketHeartbeatJs from "./websocketIm";
import { getToken, removeStorageToken } from '@/utils/auth'
import { parseTime } from "@/filters/index.js"
import { logout, ErrorType, imageLoad, MessageInfoType, MessageTargetType } from "./ChatUtils";

class RequestUtils {
	constructor() {
		this.instance = null;
	}

	/**
	 * 单例构造方法，构造一个广为人知的接口，供用户对该类进行实例化
	 * @returns {RequestUtils}
	 */
	static getInstance() {
		if(!this.instance) {
			this.instance = new RequestUtils();
		}
		return this.instance;
	}

	/**
	 * websocket 连接处理
	 * @param self vue
	 */
	webSocketOperation(self) {
		let websocketHeartbeatJs = new WebsocketHeartbeatJs({
			url: window.config.VUE_APP_IM_WS + '?token=' + getToken()
		});
		websocketHeartbeatJs.onopen = function() {
			websocketHeartbeatJs.send('{"code":' + MessageInfoType.MSG_READY + "}");
			console.log('链接成功');
		};
		websocketHeartbeatJs.onmessage = function (event) {
			console.log('接受到的消息', event);
			
			let data = event.data;
			let sendInfo = JSON.parse(data);
			self.$store.commit('setmessages', sendInfo)
			// self.$store.commit("addMessage",sendInfo.message);
			// console.log('message.fromId', sendInfo.message.fromId);
			// console.log('currentChat.id', self.$store.state.im.currentChat.id);
			// 真正的消息类型
			if(sendInfo.code === MessageInfoType.MSG_MESSAGE) {
				let message = sendInfo.message;
				message.label = 'info';
				message.timestamp = parseTime(new Date(message.timestamp), '{y}-{m}-{d} {h}:{i}:{s}');
				// 发送给个人
				if(message.type === MessageTargetType.FRIEND) {
					// 接受人是当前的聊天窗口
					if(String(message.fromId) === String(self.$store.state.im.currentChat.id)) {
						self.$store.commit("addMessage", message);
					} else {
						self.$store.commit("setUnReadCount", message);
						self.$store.commit("addUnreadMessage", message);
					}
				} else if(message.type === MessageTargetType.CHAT_GROUP) {
					// 接受人是当前的聊天窗口
					if(String(message.id) === String(self.$store.state.im.currentChat.id)) {
						console.log(String(message.fromId) ,self.$store.state.im.user.userId)
						if(String(message.fromId) !== self.$store.state.im.user.userId) {
							self.$store.commit("addMessage", message);
						}
					} else {
						self.$store.commit("setUnReadCount", message);
						self.$store.commit("addUnreadMessage", message);
					}
				}
				self.$store.commit("setLastMessage", message);
				// 每次滚动到最底部
				self.$nextTick(() => {
					imageLoad("sectionmain");
				});
			}
		};

		websocketHeartbeatJs.onreconnect = function() {
			console.log("reconnecting...");
		};

		let count = 0;
		websocketHeartbeatJs.onerror = function() {
			RequestUtils.getInstance()
				.catch(error => {
					count++;
					if(ErrorType.NET_ERROR === error.toString()) {
						self.$Message.error("网络断开，正在重连...");
					} else if(ErrorType.FLUSH_TOKEN_ERROR === error) {
						count = 25;
					}
				});
			//重连次数大于24 退出登录
			if(count > 24) {
				count = 0;
				logout(self);
			}
		};
		self.$store.commit("setWebsocket", websocketHeartbeatJs);
	}
}

export default RequestUtils;